# -*- coding: utf-8 -*-
# @File     : api.py
# @Author   : bingjia
# @Time     : 2020/8/7 9:28
# @Desc     : 索引api视图

from concurrent import futures

from ..base.api import viewsets
from ..base.api import response
from ..permissions.services import user_has_perm

from . import services
from . import serializers


class SearchViewSet(viewsets.ViewSet):
    """
    索引视图
    """
    def list(self, request, **kwargs):
        text = request.QUERY_PARAMS.get('text', "")
        project_id = request.QUERY_PARAMS.get('project', None)

        project = self._get_project(project_id)

        result = {}
        with futures.ThreadPoolExecutor(max_workers=4) as executor:
            futures_list = []
            if user_has_perm(request.user, "view_datas", project):
                datas_future = executor.submit(self._search_datas, project, text)
                datas_future.result_key = "datas"
                futures_list.append(datas_future)
            if user_has_perm(request.user, "view_equipments", project):
                equipments_future = executor.submit(self._search_equipments, project, text)
                equipments_future.result_key = "equipments"
                futures_list.append(equipments_future)
            if user_has_perm(request.user, "view_infos", project):
                infos_future = executor.submit(self._search_infos, project, text)
                infos_future.result_key = "infos"
                futures_list.append(infos_future)

            for future in futures.as_completed(futures_list):
                data = []
                try:
                    data = future.result()
                except Exception as exc:
                    print('%s generated an exception: %s' % (future.result_key, exc))
                finally:
                    result[future.result_key] = data

        result["count"] = sum(map(lambda x: len(x), result.values()))
        return response.Ok(result)

    def _search_datas(self, project, text):
        """
        获取数据信息
        :return:
        """
        queryset = services.search_datas(project, text)
        serializer = serializers.DataSearchResultsSerializer(queryset, many=True)
        return serializer.data

    def _search_infos(self, project, text):
        """
        获取数据信息
        :return:
        """
        queryset = services.search_datas(project, text)
        serializer = serializers.InfoSearchResultsSerializer(queryset, many=True)
        return serializer.data

    def _search_equipments(self, project, text):
        """
        获取数据信息
        :return:
        """
        queryset = services.search_datas(project, text)
        serializer = serializers.EquipmentSearchResultsSerializer(queryset, many=True)
        return serializer.data